﻿using AM.Communication.Entity;
using AviewMotionUI.MachineLife;
using AviewMotionUI.ProductionStatistics;
using DCAPI.Data;
using FinalTestMachine.Connect;
using FinalTestMachine.Funs;
using FinalTestMachine.Motion;
using FinalTestMachine.Motion.Aixs;
using FinalTestMachine.Motion.Process;
using FinalTestMachine.Motion.Process.RunModel;
using FinalTestMachine.Motion.Process.SubProcess;
using FinalTestMachine.Motion.Products;
using FinalTestMachine.View;
using FinalTestMachine.View.MainUnits;
using FinalTestMachine.View.ZmotionView;
using IConnectDLL.Container;
using LanCustomControldll;
using LanCustomControldll.Unit_ListMsg;
using LanguageControlBase.Wpf;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FinalTestMachine
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            App.Current.MainWindow = this;
            uc_Log.SetMaxListMsgNum(3);

            var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            var versionDescriptions = System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Reflection.AssemblyDescriptionAttribute), false);
            string description = ((System.Reflection.AssemblyDescriptionAttribute)versionDescriptions[0]).Description;
            this.Title = $"Motion Control" + "    Version:"
                + version;

            LanguageManager.LanguageSearchHelper.CreateInstrance();

            CreateGroupBoxOfShowingStationStatus();
            CreateGroupBoxOfShowFixtureStatus();
            CreateDataGridOfShowingTestResult(1);
        }

        //窗体位置
        private readonly WndStartPositionHelper wndStartPositionHelper = new WndStartPositionHelper();

        private string pathWndCfg => System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MainWndStartPositionCfg.ini");
        private readonly string Wnd_Section = "Window";
        private double Wnd_left = 0;
        private double Wnd_Top = 0;
        private double Wnd_Width = 1300;
        private double Wnd_Height = 850;
        private bool IsCloseWritePosition = false;

        private void Ini_Write(string Key, string _value)
        {
            INIAPI.IniAPI.INIWriteValue(pathWndCfg, Wnd_Section, Key, _value);
        }

        private string Ini_Read(string Key)
        {
            return INIAPI.IniAPI.INIGetStringValue(pathWndCfg, Wnd_Section, Key, "0");
        }

        private void ReadWndCfg()
        {
            if (!System.IO.File.Exists(pathWndCfg))
            {
                using (System.IO.File.Create(pathWndCfg))
                { };

                Fun_WritePositionToCfg();
                Ini_Write("IsCloseWritePosition", IsCloseWritePosition.ToString());
                IsCloseWritePosition = true;
            }
            else
            {
                Wnd_left = double.Parse(Ini_Read("Wnd_left"));
                Wnd_Top = double.Parse(Ini_Read("Wnd_Top"));
                Wnd_Width = double.Parse(Ini_Read("Wnd_Width"));
                Wnd_Height = double.Parse(Ini_Read("Wnd_Height"));
                IsCloseWritePosition = bool.Parse(Ini_Read("IsCloseWritePosition"));
            }
        }

        private void Fun_WritePositionToCfg()
        {
            try
            {
                Ini_Write("Wnd_left", Wnd_left.ToString());
                Ini_Write("Wnd_Top", Wnd_Top.ToString());
                Ini_Write("Wnd_Width", Wnd_Width.ToString());
                Ini_Write("Wnd_Height", Wnd_Height.ToString());
            }
            catch
            {
            }
        }

        private void Fun_ReadWndPositionFromCfg()
        {
            Wnd_left = double.Parse(Ini_Read("Wnd_left"));
            Wnd_Top = double.Parse(Ini_Read("Wnd_Top"));
            Wnd_Width = double.Parse(Ini_Read("Wnd_Width"));
            Wnd_Height = double.Parse(Ini_Read("Wnd_Height"));
        }

        private List<TextBlock> stationStatusList = new List<TextBlock>();
        private List<TextBlock> stationFixtureList = new List<TextBlock>();
        private List<DataGrid> testResultList = new List<DataGrid>();
        private List<LanTextBlock> fixtureEnableList = new List<LanTextBlock>();
        private List<LanTextBlock> fixtureOCList = new List<LanTextBlock>();
        private List<LanTextBlock> currentList = new List<LanTextBlock>();
        private int rows = 0;
        private void CreateGroupBoxOfShowingStationStatus()
        {
            //获取所要创建的工站个数
            int stationSum = GlobalParams.WorkstationSum;
            int rowOffset = 1 + (GlobalParams.WorkstationSum % 2 == 0 ? 0 : 1);
            rows = GlobalParams.WorkstationSum / 2 + rowOffset;
            //准备行和列数量
            for (int i = 0; i < rows; i++)
            {
                workstationStatus.RowDefinitions.Add(new RowDefinition());
            }
            for (int i = 0; i < 3; i++)
            {
                workstationStatus.ColumnDefinitions.Add(new ColumnDefinition());
            }

            bool whetherEven = (stationSum - 2) / 2 % 2 == 0;

            //分别创建对应的GroupBox对象
            for (int i = 0; i < stationSum; i++)
            {
                GroupBox control = new GroupBox();
                control.Style = (Style)FindResource("CustomGroupBoxStyle");
                //设置该控件对应的行数
                Grid.SetRow(control, GetRow(i));
                //设置该控件对应的列数
                Grid.SetColumn(control, GetColumn(i));
                //其他配置项
                control.Margin = new Thickness(5);
                control.Header = $"工位{i+1}";
                #region 内部文本框
                Grid grid = new Grid();
                TextBlock stationStatus = new TextBlock()
                {
                    Text = "Test",
                    FontSize = 10
                };
                Grid.SetRow(stationStatus, 0);
                TextBlock stationFixture = new TextBlock()
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 16,
                    Text = ((char)((int)('A') + i)).ToString()
                };
                Grid.SetRow(stationFixture, 1);
                grid.Children.Add(stationStatus);
                grid.Children.Add(stationFixture);
                stationStatusList.Add(stationStatus);
                stationFixtureList.Add(stationFixture);
                //将网格控件添加至组控件中
                control.Content = grid;
                #endregion
                //放入对应GroupBox中
                workstationStatus.Children.Add(control);
            }   

            //创建状态显示对象
            tb_MachineState = new LanTextBlock()
            {
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
                Background = Brushes.Red,
                LanText = "Not Home",
                Padding = new Thickness(5)

            };
            Grid.SetColumn(tb_MachineState, 1);
            Grid.SetRow(tb_MachineState, 1);
            if (whetherEven)
            {
                Grid.SetRowSpan(tb_MachineState, 2);
            }
            workstationStatus.Children.Add(tb_MachineState);
        }
        private void CreateGroupBoxOfShowFixtureStatus()
        {
            for (int i = 0; i < GlobalParams.WorkstationSum; i++)
            {
                grid_fixtureStatus.RowDefinitions.Add(new RowDefinition() { });
            }
            for (int i = 0; i < 9; i++)
            {
                if(i == 2 || i == 5)
                {
                    grid_fixtureStatus.ColumnDefinitions.Add(new ColumnDefinition() { MaxWidth = 10 });
                }
                else
                    grid_fixtureStatus.ColumnDefinitions.Add(new ColumnDefinition());
            }

            for (int i = 0; i < GlobalParams.WorkstationSum; i++)
            {
                LanTextBlock fixtureNo = new LanTextBlock()
                {
                    LanText = "治具" + ((char)(65 + i)).ToString() + "：",
                    HorizontalAlignment = HorizontalAlignment.Right,
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 15,
                    Margin = new Thickness(0, 0, 0, 0),
                };
                Grid.SetColumn(fixtureNo, 0);
                Grid.SetRow(fixtureNo, i);
                LanTextBlock fixtureEnable = new LanTextBlock()
                {
                    Background = Brushes.Green,
                    LanText = "启用中",
                    TextAlignment = TextAlignment.Center,
                    Width = 70,
                    FontSize = 15,
                    FontWeight = FontWeights.Bold,
                    FontStyle = FontStyles.Oblique,
                    VerticalAlignment = VerticalAlignment.Center,
                    Padding = new Thickness(0, 5, 0, 5),
                };

                fixtureEnableList.Add(fixtureEnable);
                Grid.SetRow(fixtureEnable, i);
                Grid.SetColumn(fixtureEnable, 1);

                LanTextBlock openCloseSensor = new LanTextBlock()
                {
                    LanText = "开合感应" + "：",
                    FontSize = 15,
                    HorizontalAlignment = HorizontalAlignment.Right,
                    VerticalAlignment = VerticalAlignment.Center,
                    Margin = new Thickness(0, 0, 0, 0),
                };
                Grid.SetColumn(openCloseSensor, 3);
                Grid.SetRow(openCloseSensor, i);
                LanTextBlock ocSensorEnable = new LanTextBlock()
                {
                    Background = Brushes.Green,
                    LanText = "启用中",
                    TextAlignment = TextAlignment.Center,
                    Width = 70,
                    FontSize = 15,
                    FontWeight = FontWeights.Bold,
                    FontStyle = FontStyles.Oblique,
                    VerticalAlignment = VerticalAlignment.Center,
                    Padding = new Thickness(0, 5, 0, 5),
                };
                fixtureOCList.Add(ocSensorEnable);
                Grid.SetRow(ocSensorEnable, i);
                Grid.SetColumn(ocSensorEnable, 4);

                LanTextBlock currentNote = new LanTextBlock()
                {
                    LanText = $"工位{i+1}" + "：",
                    FontSize = 15,
                    HorizontalAlignment = HorizontalAlignment.Right,
                    VerticalAlignment = VerticalAlignment.Center,
                    Margin = new Thickness(0, 0, 0, 0),
                };
                Grid.SetRow(currentNote, i);
                Grid.SetColumn(currentNote, 6);
                LanTextBlock currentValue = new LanTextBlock()
                {
                    Background = Brushes.Green,
                    LanText = "0",
                    TextAlignment = TextAlignment.Center,
                    Width = 70,
                    FontSize = 15,
                    FontWeight = FontWeights.Bold,
                    FontStyle = FontStyles.Oblique,
                    VerticalAlignment = VerticalAlignment.Center,
                    Padding = new Thickness(0, 5, 0, 5),
                };
                currentList.Add(currentValue);
                Grid.SetRow(currentValue, i);
                Grid.SetColumn(currentValue, 7);

                grid_fixtureStatus.Children.Add(fixtureNo);
                grid_fixtureStatus.Children.Add(fixtureEnable);
                grid_fixtureStatus.Children.Add(openCloseSensor);
                grid_fixtureStatus.Children.Add(ocSensorEnable);
                grid_fixtureStatus.Children.Add(currentNote);
                grid_fixtureStatus.Children.Add(currentValue);
            }
        }
        private void CreateDataGridOfShowingTestResult()
        {
            for (int i = 0; i < 2 * GlobalParams.WorkstationSum -1; i++)
            {
                if (i % 2 != 0) {
                    unit_ResultListInfo.grid_testResult.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(5), });
                }
                else
                {
                    unit_ResultListInfo.grid_testResult.ColumnDefinitions.Add(new ColumnDefinition());
                }
            }

            DataGridTemplateColumn CreateColumn(string Header, string path, int width)
            {
                DataGridTemplateColumn dataGridTemplateColumn = new DataGridTemplateColumn()
                {
                    Width = width,
                    Header = Header,
                };
                DataTemplate dataTemplate = new DataTemplate();
                TextBlock textBlock = new TextBlock()
                {
                    Foreground = Brushes.Black,
                };
                textBlock.SetBinding(TextBlock.BackgroundProperty, new Binding("bdBrush"));
                textBlock.SetBinding(TextBlock.TextProperty, new Binding(path));
                var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
                textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Black);
                dataTemplate.VisualTree = textBlockFactory;
                dataGridTemplateColumn.CellTemplate = dataTemplate;
                return dataGridTemplateColumn;
            }

            int stationCount = 1;
            for (int i = 0; i < 2 * GlobalParams.WorkstationSum - 1; i++) {
                if (i % 2 != 0)
                {
                    continue;
                }
                int column = i / 3;
                DataGrid dataGrid = new DataGrid() {
                    MaxHeight = 500,
                    AutoGenerateColumns = false,
                    IsReadOnly = true,
                    Style = (Style)FindResource("FlatDataGridStyle"),
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                };

                dataGrid.Columns.Add(CreateColumn("Name", "Name", 50));
                dataGrid.Columns.Add(CreateColumn("Value", "Value", 50));
                dataGrid.Columns.Add(CreateColumn("Result", "Result", 50));

                dataGrid.ItemsSource = unit_ResultListInfo.stationResultList[stationCount-1];
                stationCount++;
                testResultList.Add(dataGrid);
                Grid.SetColumn(dataGrid, i);

                unit_ResultListInfo.grid_testResult.Children.Add(dataGrid);
            }
        }
        private void CreateDataGridOfShowingTestResult(int index)
        {
            int NumOfShowingTable = 3;
            DataGridTemplateColumn CreateColumn(string Header, string path, int width)
            {
                DataGridTemplateColumn dataGridTemplateColumn = new DataGridTemplateColumn()
                {
                    Width = width,
                    Header = Header,
                };
                DataTemplate dataTemplate = new DataTemplate();
                var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));

                textBlockFactory.SetBinding(
                    TextBlock.BackgroundProperty,
                    new Binding("bdBrush")  // 绑定数据源的 bdBrush 属性
                );

                // 设置固定 Foreground 为黑色
                textBlockFactory.SetValue(
                    TextBlock.ForegroundProperty,
                    Brushes.Black
                );

                // 绑定 Text 到 Value 属性
                textBlockFactory.SetBinding(
                    TextBlock.TextProperty,
                    new Binding(path)    // 绑定数据源的 Value 属性
                );

                textBlockFactory.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
                textBlockFactory.SetValue (TextBlock.VerticalAlignmentProperty, VerticalAlignment.Center);

                // 4. 将 TextBlock 工厂设置为 DataTemplate 的可视化树
                dataTemplate.VisualTree = textBlockFactory;
                dataGridTemplateColumn.CellTemplate = dataTemplate;
                return dataGridTemplateColumn;
            }
            TabControl tc = new TabControl();
            TabItem tabItem = new TabItem();
            StackPanel stackPanel = new StackPanel();
            for (int i = 0; i < GlobalParams.WorkstationSum; i++) {
                DataGrid dataGrid = new DataGrid()
                {
                    MaxHeight = 500,
                    MaxWidth = 300,
                    AutoGenerateColumns = false,
                    IsReadOnly = true,
                    Style = (Style)FindResource("FlatDataGridStyle"),
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                    Margin = new Thickness(5,10,0,0),
                };

                dataGrid.Columns.Add(CreateColumn("Name", "Name", 70));
                dataGrid.Columns.Add(CreateColumn("Value", "Value", 60));
                dataGrid.Columns.Add(CreateColumn("Result", "Result", 80));

                dataGrid.ItemsSource = unit_ResultListInfo.stationResultList[i];

                if (i % NumOfShowingTable == 0)
                {
                    tabItem = new TabItem()
                    {
                        Header = "Group " + index++,
                        Style = (Style)FindResource("FlatTabItemStyle"),
                    };
                    stackPanel = new StackPanel() { 
                        Orientation = Orientation.Horizontal,
                    };
                    tabItem.Content = stackPanel;
                    tc.Items.Add(tabItem);
                }
                stackPanel.Children.Add(dataGrid);
            }
            unit_ResultListInfo.grid_testResult.Children.Add(tc);
        }
    
        private LanTextBlock tb_MachineState;
        private int GetRow(int index)
        {
            int totalRows = rows;
            int middle = GlobalParams.WorkstationSum / 2;

            if (index == 0)
            {
                return totalRows;
            }
            else if (index < middle)
            {
                return totalRows - index - 1;
            }
            else if (index == middle && GlobalParams.WorkstationSum % 2 == 0)
            {
                return 0;
            }
            else if (index == middle && GlobalParams.WorkstationSum % 2 != 0)
            {
                return totalRows - index - 1;
            }
            else if (index < GlobalParams.WorkstationSum)
            {
                return totalRows - GlobalParams.WorkstationSum % index - 1;
            }
            return -1;
        }
        private int GetColumn(int index)
        {
            int middle = GlobalParams.WorkstationSum / 2;
            if (index == 0 || (index == middle && GlobalParams.WorkstationSum % 2 == 0))
            {
                return 1;
            }
            else if (index <= middle)
            {
                return 2;
            }
            else if (index < GlobalParams.WorkstationSum)
            {
                return 0;
            }
            return -1;
        }

        private void flushStationStatus()
        {
            tb_MachineState.LanText = Motion.StaticInitial.Motion.MotionStateInfo.MotionState;
            tb_AssemblyInfo.Text = $"Version:{System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()}";
            tb_MachineState.Background = Motion.StaticInitial.Motion.MotionStateInfo.MotionStateColor;


            for (int i = 0; i < GlobalParams.WorkstationSum; i++)
            {
                stationFixtureList[i].Text = RotatedMovNextHelper.tagPos[i];
            }
        }

        private void flushFixtureStatus()
        {
            for (int i = 0; i < Process_TestStationBase.testStaionList.Count; i++)
            {
                Process_TestStationBase Temp = Process_TestStationBase.testStaionList[i];
                if (Temp.IsTesting)
                {
                    if (Temp.CurrentProduct != null && Temp.CurrentProduct.Number.Length > 0)
                    {
                        stationStatusList[i].Text = "testing..." + "SN:" + Temp.CurrentProduct.Number;
                    }
                    else
                    {
                        stationStatusList[i].Text = "testing...NoSN";
                    }
                }
                else
                {
                    stationStatusList[i].Text = "No testing...";
                }
            }
        }

        private void flushFixtureInfo()
        {
            for (int i = 0; i < GlobalParams.WorkstationSum; i++) {
                string path = "IsUseSocket" + ((char)(65 + i)).ToString();
                if (GlobalParams.GetFieldValue<bool>(FunSocketSettings.Cur, path))
                {
                    fixtureEnableList[i].LanText = "启用";
                    fixtureEnableList[i].Background = Brushes.Green;
                }
                else
                {
                    fixtureEnableList[i].LanText = "禁用";
                    fixtureEnableList[i].Background = Brushes.Red;
                }
                path = "IsUseSocket" + ((char)(65 + i)).ToString() + "Sensor";
                if (GlobalParams.GetFieldValue<bool>(FunSocketSettings.Cur, path))
                {
                    fixtureOCList[i].LanText = "启用";
                    fixtureOCList[i].Background = Brushes.Green;
                }
                else
                {
                    fixtureOCList[i].LanText = "禁用";
                    fixtureOCList[i].Background = Brushes.Red;
                }

                try
                {                    
                    //单个程控电源使用的频道数量
                    path = $"Site{i+1}IsUse";
                    if(GlobalParams.GetFieldValue<bool>(FunStationSettings.Cur, path))
                    {
                        currentList[i].LanText = "启用";
                        currentList[i].Background = Brushes.Green;
                    }
                    else
                    {
                        currentList[i].LanText = "禁用";
                        currentList[i].Background= Brushes.Red;
                    }
                    
                }
                catch(Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                
            }
            
        }

        private void ShowUI()
        {
            unit_MainBtns.ShowUI();
            ProductInfoHlep.ShowUI();

            string temp = "";
            RM_dll2.ExtraMsgHelper.ScanExtraMsg(s =>
            {
                temp += s.Info;
            });

            #region 站位状态
            
            flushStationStatus();

            flushFixtureStatus();

            flushFixtureInfo();
            #endregion

            if (Menu_Main.menu_Motion.IsEnabled)
            {
                SetLimit(true);
            }
            else
            {
                SetLimit(false);
            }

            if (Funs.FunCommSelection.Cur.IsUseMes && !Funs.FunCommSelection.Cur.IsUseSpotCheck)
            {
                this.rect1.Fill = Brushes.Green;
            }
            else
            {
                this.rect1.Fill = Brushes.Red;
            }
        }

        private void SetLimit(bool bl)
        {
            Connect.SiteConnectManager.Cur.SetLimit(bl);
        }

        private async void MotionInitial()
        {
            await Task.Run(() =>
            {
                try
                {
                    CardInital.Initial();
                    Motion.StaticInitial.Initial();
                }
                catch (Exception ex)
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        if (Wnd_ProcessBar.Cur != null)
                        {
                            CardInital.ReportInfoProcessBarEvent += Wnd_ProcessBar.CreateInstrance().WriteProcessLog;
                        }
                        Wnd_ProcessBar.SingleClose();
                        MessageBox.Show(ex.Message);
                    });
                }
            });

            if (Wnd_ProcessBar.Cur != null)
            {
                CardInital.ReportInfoProcessBarEvent += Wnd_ProcessBar.CreateInstrance().WriteProcessLog;
            }

            Wnd_ProcessBar.SingleClose();
            MotionWndViewModelHelper motionWindowViewModel = MotionWndViewModelHelper.CreateInstrance();
            motionWindowViewModel.ExtraShowUIEventHandler += ShowUI;
            motionWindowViewModel.Initial();
            //总运行信息
            StaticInitial.Motion.WriteToUserEvent += uc_Log.WriteToUser;
            StaticInitial.Motion.LanWriteToUserEvent += uc_Log.WriteToUser;
            Motion.Process.Process_ResMachine.Cur.WriteToUserEvent += uc_Log.WriteToUser;
            Motion.Process.Process_AutoRun.Cur.WriteToUserEvent += uc_Log.WriteToUser;
            //测试工位信息
            AddStationLogPage();
            //错误信息
            RM_dll2.AllErrInfoRecord.WriteErrToUserEvent += s => uc_ErrorLog.WriteToUser(s, Brushes.Red, false);
            StaticInitial.Motion.actionClearErrEventHandler += uc_ErrorLog.ClearMsg;

            Motion.Process.Process_AutoRun.Cur.ClearUIAction += Cur_ClearUIAction;
            Motion.Process.Process_AutoRun.Cur.LoadMsgEventHandler += AddLoadUnLoadTip;
            Motion.Process.Process_AutoRun.Cur.result_show_EventHandler += WriteResult;
            Motion.Process.Process_AutoRun.Cur.Site_BottomShowAction += Cur_Site_BottomShowAction;

            //该方法所有工位测试结果输出到列表里面
            Process_AutoRun.Cur.Site_ShowAction += unit_ResultListInfo.AddSiteXData;

            ProductionStatisticsManger.CreateInstance();
            Process_ResMachine.Cur.ClearErrInfo += ClearErrInfo;

            SocketSpotInspection.Cur.WriteToUserEvent += uc_Log.WriteToUser;

            Connect.ConnectFactory.TCP_ScanCode.RecevieMsgActionEventHander += ReadSN;

            MachineLifeVariableManger.Current.SetGetModelNameFunc(() => ParamPath_Motion.SelectedDirName);

            SpotInspectionFacility.ProductInfoManger.Cur.SetGetModelNameFunc(() => ParamPath_Motion.SelectedDirName);

            this.IsEnabled = true;

            string[] probeName = new string[GlobalParams.WorkstationSum];
            for (int i = 0; i < GlobalParams.WorkstationSum; i++)
            {
                probeName[i] = (char)(65 + i) + "治具探针";
            }
            //注册机种
            MachineLifeVariableManger.Current.RegisterComponentType(OtherParamHelper.TYPE_COMPONENT_PROBE, probeName);
            MachineLifeVariableManger.Current.ChangeModel(View.WorkItemManagerHelper.LoadedName);

            AM.Communication.ConnectUIBuilder.SetUIWithConnect(Menu_Main.Communication, AM.Communication.ConnectBuilder.ConnectInfoList);

            //AM.Communication.ConnectUIBuilder.SetUIWithConnect(Menu_Main.menu_LightSourceSetting, AM.Communication.ConnectBuilder.ConnectInfoList);
            CreateCommunicationUI();
        }
        //支持翻译连接名称
        bool IsRegisterUI = false;

        private void AddStationLogPage()
        {

            foreach (var item in Process_TestStationBase.testStaionList)
            {
                LanTabItem lanTabItem = new LanTabItem();
                lanTabItem.LanHeader = item.Name;
                lanTabItem.Style = (Style)FindResource("FlatTabItemStyle");

                UC_ListMsg uC_ListMsg = new UC_ListMsg();
                item.WriteToUserEvent += uC_ListMsg.WriteToUser;
                lanTabItem.Content = uC_ListMsg;
                
                tabControl_allLog.Items.Add(lanTabItem);
            }
        }

        private void CreateCommunicationUI()
        {
            if (IsRegisterUI == false)
            {
                IConnectDLL.ConnectManagerHelper.RegisterMenu(Menu_Main.menu_LightSourceSetting, s =>
                {
                    if (s == null) return new LanguageControlBase.Wpf.LanMenuItem();
                    if (s.IsNodeInfo == false)
                    {
                        return new LanguageControlBase.Wpf.LanMenuItem() { LanHeader = (s as WindowGroupInfo).GroupName };
                    }
                    else
                    {
                        var node = s as WindowNodeInfo;
                        var m = new LanguageControlBase.Wpf.LanMenuItem();
                        m.LanHeader = node.Title;
                        m.Click += (k, r) => node.Show();
                        return m;
                    }
                });
                IsRegisterUI = true;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                LanguageManager.LanguageSearchHelper.AddLanguagMenuItem(Menu_Main.TopMenu);
                /*ReadWndCfg();
                this.Top = Wnd_Top;
                this.Left = Wnd_left;
                this.Width = Wnd_Width;
                this.Height = Wnd_Height;
                wndStartPositionHelper.SetWndStartPosition(this);*/

                this.IsEnabled = false;
                Wnd_ProcessBar.SingleShow();
                CardInital.ReportInfoProcessBarEvent += Wnd_ProcessBar.CreateInstrance().WriteProcessLog;
                MotionInitial();
            }
            catch (Exception ex)
            {
                MessageBox.Show(AM.Tools.ExceptionHelper.GetInnerExceptionMessageAndStackTrace(ex));
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            try
            {
                if (IsCloseWritePosition)
                {
                    Wnd_Top = this.Top;
                    Wnd_left = this.Left;
                    Wnd_Width = this.Width;
                    Wnd_Height = this.Height;
                    Fun_WritePositionToCfg();
                }

                wndStartPositionHelper.SaveWndCurrentPosition(this);
                MotionWndViewModelHelper motionWindowViewModel = MotionWndViewModelHelper.CreateInstrance();
                motionWindowViewModel.Close();

                StaticInitial.Close();
            }
            catch (Exception)
            {
            }
            finally
            {
                App.Current.Shutdown(0);
                Environment.Exit(0);
            }
        }

        private void Cur_Site_BottomShowAction(string obj)
        {
            this.Dispatcher.Invoke(() =>
            {
                tb_UnLoadProductInfo.Text = obj;
            });
        }

        private void Cur_ClearUIAction()
        {
            this.Dispatcher.Invoke(() =>
            {
                tb_SN.Text = "";
                tb_SnGetTime.Text = "";
                unit_ResultListInfo.Clear();
                tb_UnLoadProductInfo.Text = "";
            });
        }

        /// <summary>
        /// 添加上料提示
        /// true:等待上料
        /// false:上料结束
        /// </summary>
        private void AddLoadUnLoadTip(string str, Brush brush)
        {
            this.Dispatcher.Invoke(() =>
            {
                tb_LoadUnLoadTip.LanText = str;
                tb_LoadUnLoadTip.Background = brush;
            });
        }

        private void WriteResult(string str, Brush brush)
        {
            this.Dispatcher.Invoke(() =>
            {
                tb_TestState.Text = str;
                gd_TestState.Background = brush;
            });
        }

        /// <summary>
        /// 读取SN
        /// </summary>
        /// <param name="sn"></param>
        public void ReadSN(string sn)
        {
            this.Dispatcher.Invoke(() =>
            {
                if (!string.IsNullOrEmpty(sn) & sn.ToLower() != "noread")
                {
                    tb_SnGetTime.Text = DateTime.Now.ToString();
                    tb_SN.Text = sn;
                }
            });
        }

        public void ClearErrInfo()
        {
            this.Dispatcher.Invoke(() =>
            {
                uc_ErrorLog.ClearMsg();
            });
        }

        private void btn_Clear_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("确定清除当前产量信息?", "清除警告", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                {
                    ProductNumberManager.Cur.Clear();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 手动输入确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Process_AutoRun.Cur.SN = tb_SN.Text;
            if (Funs.FunCommSelection.Cur.IsUseMes)
            {
            }
            Process_AutoRun.Cur.WriteToUser($"SN检查成功，SN：{Process_AutoRun.Cur.SN}", Brushes.Green, true);
        }

        private void item_3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Tab)
            {
                Motion.StaticInitial.Motion.CurOrder.ResOKFlag.SetFlag();
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Are you sure to exit？", "Please Confirm", MessageBoxButton.YesNo);

            if (result != MessageBoxResult.Yes)
            {
                e.Cancel = true;
            }
        }
    }
}